#include "systemconfigdialog.h"
#include <QApplication>
#include <QStandardPaths>
#include <QDir>
#include <QSettings>
#include <QDebug>
#include <QStorageInfo>
#include <QSysInfo>
#include <QFileInfo>

/**
 * 重构后的SystemConfigDialog实现
 * 重构原则：简化复杂性，提高可读性和用户体验
 * Martin Fowler: Extract Method, Replace Complex Conditional with Polymorphism
 */

SystemConfigDialog::SystemConfigDialog(QWidget* parent)
    : QDialog(parent)
    , m_configChanged(false)
    , m_updateTimer(new QTimer(this))
{
    setWindowTitle(tr("系统配置"));
    setModal(true);

    // 禁止调整大小
    setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);
    
    // 针对不同平台设置合适的对话框尺寸
#ifdef Q_OS_MACOS
    // macOS 需要更大的尺寸来避免控件压缩
    setFixedSize(550, 600);
#else
    // Windows 和 Linux 使用原有尺寸
    setFixedSize(433, 400);
#endif

    setupUI();
    connectSignals();
    loadConfig();
    updateUI();

    // 启动定时器进行实时更新
    m_updateTimer->setInterval(2000); // 每2秒更新一次
    connect(m_updateTimer, &QTimer::timeout, this, &SystemConfigDialog::updateMemoryInfo);
    connect(m_updateTimer, &QTimer::timeout, this, &SystemConfigDialog::updateStorageInfo);
    m_updateTimer->start();
}

SystemConfigDialog::~SystemConfigDialog()
{
}

void SystemConfigDialog::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    
    // 为 macOS 设置主布局间距
#ifdef Q_OS_MACOS
    m_mainLayout->setSpacing(15);  // 增加组之间的间距
    m_mainLayout->setContentsMargins(20, 20, 20, 20);  // 增加边距
#else
    m_mainLayout->setSpacing(10);
    m_mainLayout->setContentsMargins(15, 15, 15, 15);
#endif

    setupPerformanceGroup();
    setupStorageGroup();
    setupLayoutGroup();

    // 系统信息组已移除以缩减对话框高度

    // 按钮布局 - 将按钮放在右下角
    m_buttonLayout = new QHBoxLayout();

    m_resetButton = new QPushButton(tr("恢复默认"), this);
    m_okButton = new QPushButton(tr("保存"), this);

    // 设置统一的按钮样式，移除蓝色
    QString buttonStyle = "QPushButton { "
                         "background-color: #f0f0f0; "
                         "border: 1px solid #ccc; "
                         "border-radius: 4px; "
                         "padding: 6px 12px; "
                         "color: #333; "
                         "} "
                         "QPushButton:hover { "
                         "background-color: #e0e0e0; "
                         "border-color: #999; "
                         "} "
                         "QPushButton:pressed { "
                         "background-color: #d0d0d0; "
                         "}";

    m_resetButton->setStyleSheet(buttonStyle);
    m_okButton->setStyleSheet(buttonStyle);

    m_buttonLayout->addStretch();  // 添加弹性空间，将按钮推到右边
    m_buttonLayout->addWidget(m_resetButton);
    m_buttonLayout->addWidget(m_okButton);

    m_mainLayout->addLayout(m_buttonLayout);
}

void SystemConfigDialog::setupPerformanceGroup()
{
    m_performanceGroup = new QGroupBox(tr("性能设置"), this);
    QGridLayout* layout = new QGridLayout(m_performanceGroup);
    
    // 针对 macOS 优化布局间距
#ifdef Q_OS_MACOS
    layout->setSpacing(10);
    layout->setContentsMargins(15, 15, 15, 15);
#else
    layout->setSpacing(6);
    layout->setContentsMargins(10, 10, 10, 10);
#endif

    // 内存性能策略
    layout->addWidget(new QLabel(tr("内存性能策略:")), 0, 0);
    m_memoryStrategyCombo = new QComboBox(this);
    m_memoryStrategyCombo->addItem(tr("节能模式"), static_cast<int>(MemoryStrategy::PowerSaving));
    m_memoryStrategyCombo->addItem(tr("平衡模式"), static_cast<int>(MemoryStrategy::Balanced));
    m_memoryStrategyCombo->addItem(tr("高性能模式"), static_cast<int>(MemoryStrategy::HighPerformance));
    m_memoryStrategyCombo->addItem(tr("极致模式"), static_cast<int>(MemoryStrategy::Extreme));
    layout->addWidget(m_memoryStrategyCombo, 0, 1);

    m_memoryInfoLabel = new QLabel(this);
    m_memoryInfoLabel->setWordWrap(true);
    m_memoryInfoLabel->setStyleSheet("QLabel { color: #666; font-size: 12px; }");
    layout->addWidget(m_memoryInfoLabel, 1, 0, 1, 2);

    // 页面处理质量
    layout->addWidget(new QLabel(tr("页面处理质量:")), 2, 0);
    m_processingQualityCombo = new QComboBox(this);
    m_processingQualityCombo->addItem(tr("快速模式 (150 DPI)"), static_cast<int>(ProcessingQuality::Fast));
    m_processingQualityCombo->addItem(tr("标准模式 (200 DPI)"), static_cast<int>(ProcessingQuality::Standard));
    m_processingQualityCombo->addItem(tr("高质量模式 (300 DPI)"), static_cast<int>(ProcessingQuality::High));
    m_processingQualityCombo->addItem(tr("极致模式 (600 DPI)"), static_cast<int>(ProcessingQuality::Extreme));
    layout->addWidget(m_processingQualityCombo, 2, 1);

    m_qualityInfoLabel = new QLabel(this);
    m_qualityInfoLabel->setWordWrap(true);
    m_qualityInfoLabel->setStyleSheet("QLabel { color: #666; font-size: 12px; }");
    layout->addWidget(m_qualityInfoLabel, 3, 0, 1, 2);

    // 为 macOS 设置列的最小宽度
#ifdef Q_OS_MACOS
    layout->setColumnMinimumWidth(0, 140);  // 标签列最小宽度
    layout->setColumnStretch(1, 1);         // 输入框列可拉伸
#endif

    m_mainLayout->addWidget(m_performanceGroup);
}

void SystemConfigDialog::setupStorageGroup()
{
    m_storageGroup = new QGroupBox(tr("存储设置"), this);
    QGridLayout* layout = new QGridLayout(m_storageGroup);
    
    // 针对 macOS 优化布局间距
#ifdef Q_OS_MACOS
    layout->setSpacing(12);  // 增加行间距
    layout->setContentsMargins(15, 15, 15, 15);  // 增加边距
#else
    layout->setSpacing(8);
    layout->setContentsMargins(10, 10, 10, 10);
#endif

    // 缓存目录
    layout->addWidget(new QLabel(tr("缓存目录:")), 0, 0);
    m_cacheDirectoryEdit = new QLineEdit(this);
    layout->addWidget(m_cacheDirectoryEdit, 0, 1);

    m_browseCacheButton = new QPushButton(tr("浏览..."), this);
    layout->addWidget(m_browseCacheButton, 0, 2);

    m_cacheSpaceLabel = new QLabel(this);
    m_cacheSpaceLabel->setStyleSheet("QLabel { color: #666; font-size: 12px; }");
    layout->addWidget(m_cacheSpaceLabel, 1, 0, 1, 3);

    // PDF输出目录
    layout->addWidget(new QLabel(tr("PDF输出目录:")), 2, 0);
    m_outputDirectoryEdit = new QLineEdit(this);
    layout->addWidget(m_outputDirectoryEdit, 2, 1);

    m_browseOutputButton = new QPushButton(tr("浏览..."), this);
    layout->addWidget(m_browseOutputButton, 2, 2);

    // 空间阈值
    layout->addWidget(new QLabel(tr("空间不足阈值:")), 3, 0);
    m_spaceThresholdSpinBox = new QSpinBox(this);
    m_spaceThresholdSpinBox->setRange(1, 10);
    m_spaceThresholdSpinBox->setSuffix(" GB");
    layout->addWidget(m_spaceThresholdSpinBox, 3, 1);

    m_spaceWarningLabel = new QLabel(tr("剩余空间少于此值时停止处理"), this);
    m_spaceWarningLabel->setStyleSheet("QLabel { color: #666; font-size: 12px; }");
    layout->addWidget(m_spaceWarningLabel, 4, 0, 1, 3);
    
    // 为 macOS 设置列的最小宽度，确保标签不会被截断
#ifdef Q_OS_MACOS
    layout->setColumnMinimumWidth(0, 140);  // 标签列最小宽度，确保完整显示
    layout->setColumnStretch(1, 2);         // 输入框列可拉伸，给予更多空间
    layout->setColumnMinimumWidth(2, 90);   // 按钮列最小宽度，确保按钮完整
#endif

    // 为浏览按钮设置统一的样式
    QString browseButtonStyle = "QPushButton { "
                               "background-color: #f0f0f0; "
                               "border: 1px solid #ccc; "
                               "border-radius: 4px; "
                               "padding: 6px 12px; "
                               "color: #333; "
                               "} "
                               "QPushButton:hover { "
                               "background-color: #e0e0e0; "
                               "border-color: #999; "
                               "} "
                               "QPushButton:pressed { "
                               "background-color: #d0d0d0; "
                               "}";

    m_browseCacheButton->setStyleSheet(browseButtonStyle);
    m_browseOutputButton->setStyleSheet(browseButtonStyle);

    m_mainLayout->addWidget(m_storageGroup);
}

void SystemConfigDialog::setupLayoutGroup()
{
    m_layoutGroup = new QGroupBox(tr("布局设置"), this);
    QGridLayout* layout = new QGridLayout(m_layoutGroup);
    
    // 针对 macOS 优化布局间距
#ifdef Q_OS_MACOS
    layout->setSpacing(10);
    layout->setContentsMargins(15, 15, 15, 15);
#else
    layout->setSpacing(6);
    layout->setContentsMargins(10, 10, 10, 10);
#endif

    // PDF默认布局
    layout->addWidget(new QLabel(tr("PDF文件默认布局:")), 0, 0);
    m_pdfLayoutCombo = new QComboBox(this);
    m_pdfLayoutCombo->addItem(tr("单栏"), static_cast<int>(LayoutMode::SingleColumn));
    m_pdfLayoutCombo->addItem(tr("双栏"), static_cast<int>(LayoutMode::TwoColumns));
    m_pdfLayoutCombo->addItem(tr("三栏"), static_cast<int>(LayoutMode::ThreeColumns));
    layout->addWidget(m_pdfLayoutCombo, 0, 1);

    // 图片默认布局
    layout->addWidget(new QLabel(tr("图片文件默认布局:")), 1, 0);
    m_imageLayoutCombo = new QComboBox(this);
    m_imageLayoutCombo->addItem(tr("单栏"), static_cast<int>(LayoutMode::SingleColumn));
    m_imageLayoutCombo->addItem(tr("双栏"), static_cast<int>(LayoutMode::TwoColumns));
    m_imageLayoutCombo->addItem(tr("三栏"), static_cast<int>(LayoutMode::ThreeColumns));
    layout->addWidget(m_imageLayoutCombo, 1, 1);

    // 为 macOS 设置列的最小宽度
#ifdef Q_OS_MACOS
    layout->setColumnMinimumWidth(0, 140);  // 标签列最小宽度
    layout->setColumnStretch(1, 1);         // 输入框列可拉伸
#endif

    m_mainLayout->addWidget(m_layoutGroup);
}

void SystemConfigDialog::connectSignals()
{
    connect(m_resetButton, &QPushButton::clicked, this, &SystemConfigDialog::onResetToDefaults);
    connect(m_browseCacheButton, &QPushButton::clicked, this, &SystemConfigDialog::onBrowseCacheDirectory);
    connect(m_browseOutputButton, &QPushButton::clicked, this, &SystemConfigDialog::onBrowseOutputDirectory);
    connect(m_okButton, &QPushButton::clicked, this, &SystemConfigDialog::onOkClicked);

    // 实时更新连接
    connect(m_memoryStrategyCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SystemConfigDialog::onMemoryStrategyChanged);
    connect(m_processingQualityCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SystemConfigDialog::onProcessingQualityChanged);
    connect(m_spaceThresholdSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &SystemConfigDialog::onSpaceThresholdChanged);
}

void SystemConfigDialog::updateUI()
{
    // 更新控件值
    int memoryIndex = m_memoryStrategyCombo->findData(static_cast<int>(m_config.memoryStrategy));
    if (memoryIndex >= 0) {
        m_memoryStrategyCombo->setCurrentIndex(memoryIndex);
    }

    int qualityIndex = m_processingQualityCombo->findData(static_cast<int>(m_config.processingQuality));
    if (qualityIndex >= 0) {
        m_processingQualityCombo->setCurrentIndex(qualityIndex);
    }

    m_cacheDirectoryEdit->setText(m_config.cacheDirectory);
    m_outputDirectoryEdit->setText(m_config.outputDirectory);
    m_spaceThresholdSpinBox->setValue(m_config.spaceThresholdGB);

    int pdfIndex = m_pdfLayoutCombo->findData(static_cast<int>(m_config.pdfDefaultLayout));
    if (pdfIndex >= 0) {
        m_pdfLayoutCombo->setCurrentIndex(pdfIndex);
    }

    int imageIndex = m_imageLayoutCombo->findData(static_cast<int>(m_config.imageDefaultLayout));
    if (imageIndex >= 0) {
        m_imageLayoutCombo->setCurrentIndex(imageIndex);
    }

    // 更新实时信息
    updateMemoryUsageDisplay();
    updateSpaceUsageDisplay();
    // updateRecommendations() 已移除，因为系统信息组被移除
}

SystemConfig SystemConfigDialog::getConfig() const
{
    SystemConfig config = m_config;

    // 从UI控件收集当前设置
    config.memoryStrategy = static_cast<MemoryStrategy>(
        m_memoryStrategyCombo->currentData().toInt());
    config.processingQuality = static_cast<ProcessingQuality>(
        m_processingQualityCombo->currentData().toInt());
    config.cacheDirectory = m_cacheDirectoryEdit->text();
    config.outputDirectory = m_outputDirectoryEdit->text();
    config.spaceThresholdGB = m_spaceThresholdSpinBox->value();
    config.pdfDefaultLayout = static_cast<LayoutMode>(
        m_pdfLayoutCombo->currentData().toInt());
    config.imageDefaultLayout = static_cast<LayoutMode>(
        m_imageLayoutCombo->currentData().toInt());

    return config;
}

void SystemConfigDialog::setConfig(const SystemConfig& config)
{
    m_config = config;
    updateUI();
}

void SystemConfigDialog::saveConfig()
{
    QSettings settings;
    
    // 详细的调试信息 - QSettings路径和组织信息
    
    settings.beginGroup("SystemConfig");

    SystemConfig config = getConfig();
    
    
    settings.setValue("memoryStrategy", SystemConfig::memoryStrategyToString(config.memoryStrategy));
    settings.setValue("processingQuality", SystemConfig::processingQualityToString(config.processingQuality));
    settings.setValue("cacheDirectory", config.cacheDirectory);
    settings.setValue("outputDirectory", config.outputDirectory);
    settings.setValue("spaceThresholdGB", config.spaceThresholdGB);
    settings.setValue("pdfDefaultLayout", SystemConfig::layoutModeToString(config.pdfDefaultLayout));
    settings.setValue("imageDefaultLayout", SystemConfig::layoutModeToString(config.imageDefaultLayout));

    settings.endGroup();
    
    settings.sync();
    
    // 验证文件是否存在
    QString filePath = settings.fileName();
    QFileInfo fileInfo(filePath);
    if (fileInfo.exists()) {
    } else {
    }
    
}

void SystemConfigDialog::loadConfig()
{
    QSettings settings;
    settings.beginGroup("SystemConfig");

    m_config.memoryStrategy = SystemConfig::memoryStrategyFromString(
        settings.value("memoryStrategy", "Balanced").toString());
    m_config.processingQuality = SystemConfig::processingQualityFromString(
        settings.value("processingQuality", "High").toString());
    m_config.cacheDirectory = settings.value("cacheDirectory",
        QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).toString();
    m_config.outputDirectory = settings.value("outputDirectory",
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).toString();
    m_config.spaceThresholdGB = settings.value("spaceThresholdGB", 2).toInt();
    m_config.pdfDefaultLayout = SystemConfig::layoutModeFromString(
        settings.value("pdfDefaultLayout", "SingleColumn").toString());
    m_config.imageDefaultLayout = SystemConfig::layoutModeFromString(
        settings.value("imageDefaultLayout", "TwoColumns").toString());

    settings.endGroup();

}

// === 槽函数实现 ===

void SystemConfigDialog::onResetToDefaults()
{
    m_config = SystemConfig(); // 使用默认构造函数
    updateUI();
    m_configChanged = true;
}

void SystemConfigDialog::onBrowseCacheDirectory()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("选择缓存目录"),
                                                   m_cacheDirectoryEdit->text());
    if (!dir.isEmpty()) {
        m_cacheDirectoryEdit->setText(dir);
        updateStorageInfo();
    }
}

void SystemConfigDialog::onBrowseOutputDirectory()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("选择PDF输出目录"),
                                                   m_outputDirectoryEdit->text());
    if (!dir.isEmpty()) {
        m_outputDirectoryEdit->setText(dir);
    }
}

void SystemConfigDialog::onMemoryStrategyChanged(int index)
{
    Q_UNUSED(index)
    updateMemoryUsageDisplay();
    updateRecommendations();
    m_configChanged = true;
}

void SystemConfigDialog::onProcessingQualityChanged(int index)
{
    Q_UNUSED(index)
    updateEstimatedSpace();
    m_configChanged = true;
}

void SystemConfigDialog::onSpaceThresholdChanged(int value)
{
    Q_UNUSED(value)
    updateSpaceUsageDisplay();
    m_configChanged = true;
}

void SystemConfigDialog::onOkClicked()
{
    
    // 直接保存配置并关闭对话框
    saveConfig();
    
    SystemConfig config = getConfig();
    emit configChanged(config);
    
    accept();
}

// === 实时信息更新方法 ===

void SystemConfigDialog::updateMemoryInfo()
{
    updateMemoryUsageDisplay();
}

void SystemConfigDialog::updateStorageInfo()
{
    updateSpaceUsageDisplay();
}

void SystemConfigDialog::updateEstimatedSpace()
{
    ProcessingQuality quality = static_cast<ProcessingQuality>(
        m_processingQualityCombo->currentData().toInt());
    QString description = ConfigStrategyCalculator::getQualityDescription(quality);
    m_qualityInfoLabel->setText(description);
}

void SystemConfigDialog::updateMemoryUsageDisplay()
{
    MemoryStrategy strategy = static_cast<MemoryStrategy>(
        m_memoryStrategyCombo->currentData().toInt());
    QString description = ConfigStrategyCalculator::getMemoryStrategyDescription(strategy);
    m_memoryInfoLabel->setText(description);
}

void SystemConfigDialog::updateSpaceUsageDisplay()
{
    QString cacheDir = m_cacheDirectoryEdit->text();
    if (QDir(cacheDir).exists()) {
        QStorageInfo storage(cacheDir);
        qint64 availableGB = storage.bytesAvailable() / 1024 / 1024 / 1024;
        m_cacheSpaceLabel->setText(tr("可用空间: %1 GB").arg(availableGB));

        if (availableGB < m_spaceThresholdSpinBox->value()) {
            m_cacheSpaceLabel->setStyleSheet("QLabel { color: red; font-weight: bold; }");
        } else {
            m_cacheSpaceLabel->setStyleSheet("QLabel { color: #666; font-size: 12px; }");
        }
    } else {
        m_cacheSpaceLabel->setText(tr("目录不存在"));
        m_cacheSpaceLabel->setStyleSheet("QLabel { color: red; }");
    }
}

void SystemConfigDialog::updateRecommendations()
{
    // 系统信息组已移除，此方法保留但不再更新UI
    // 系统信息现在通过其他方式显示（如状态栏或工具提示）
}

void SystemConfigDialog::validateConfig()
{
    // 验证目录是否存在和可写
    QString cacheDir = m_cacheDirectoryEdit->text();
    if (!QDir(cacheDir).exists()) {
        QDir().mkpath(cacheDir);
    }

    QString outputDir = m_outputDirectoryEdit->text();
    if (!QDir(outputDir).exists()) {
        QDir().mkpath(outputDir);
    }
}